import React, {useState} from 'react';
import {Modal, Spin, message, ConfigProvider} from 'antd';
import OrderBaseInfo from './OrderBaseInfo';
import OrderProducts from './OrderProducts';
import {IOrderDetail, IOrderInfo, OrderDetailViewProps} from './types';
import './style.less'; // 新增样式文件

const OrderDetailView: React.FC<OrderDetailViewProps> = ({
                                                           children,
                                                           onFetchOrder,
                                                         }) => {
  const [visible, setVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const [orderInfo, setOrderInfo] = useState<IOrderInfo | null>(null);
  const [orderDetails, setOrderDetails] = useState<IOrderDetail[]>([]);

  const fetchOrderDetail = async () => {
    try {
      setLoading(true);
      const order = await onFetchOrder();
      if (!order) {
        setVisible(false)
      }
      const {orderInfo, orderDetails}: any = order
      setOrderInfo(orderInfo || {});
      setOrderDetails(orderDetails || []);
    } catch (error) {
      message.error('获取订单详情失败');
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  const handleTrigger = async () => {
    setVisible(true);
    await fetchOrderDetail();
  };

  return (
    <ConfigProvider
      theme={{
        components: {
          Modal: {
            headerBg: '#f0f5ff',
            borderRadiusLG: 8,
            paddingMD: 24,
          },
        },
      }}
    >
      <div
        onClick={handleTrigger}
        className="order-detail-trigger"
      >
        {children}
      </div>
      <Modal
        title={<span style={{fontWeight: 600}}>订单详情</span>}
        open={visible}
        onCancel={() => setVisible(false)}
        footer={null}
        width={1000}
        destroyOnClose
        centered
        className="enhanced-order-modal"
      >
        <Spin spinning={loading} tip="加载中..." size="large">
          {orderInfo && <OrderBaseInfo data={orderInfo}/>}
          {orderDetails.length > 0 && <OrderProducts data={orderDetails}/>}
        </Spin>
      </Modal>
    </ConfigProvider>
  );
};

export default OrderDetailView;
